package com.qipay.sms.utils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.jsonwebtoken.lang.Assert;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Creator: Yao
 * Date:    2017/10/26
 * For:
 * Other:
 */
@Component
public class CodeCacheUtils {

    private static Cache<String, String> cache;
    private final static String format = "%s_%s";
    private final int validCodeLength = 4;

    private Cache<String, String> getInstance() {

        if (null == cache)
            cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MINUTES).build();

        return cache;
    }

    public String generateValidCode(String phone, String template) {

        // check
        Assert.isTrue(StringUtils.isNotBlank(phone));
        Assert.isTrue(StringUtils.isNotBlank(template));

        // init
        String key = String.format(format, phone, template);
        String validCode = getInstance().getIfPresent(key);

        // generate
        if (StringUtils.isBlank(validCode)) {
            validCode = RandomStringUtils.randomNumeric(validCodeLength);
            getInstance().put(key, validCode);
        }

        return validCode;
    }

    public String getValidCode(String phone, String template) {

        // check
        Assert.isTrue(StringUtils.isNotBlank(phone));
        Assert.isTrue(StringUtils.isNotBlank(template));

        // init
        String key = String.format(format, phone, template);
        return getInstance().getIfPresent(key);
    }
//    cache.invalidate();

    public void invalidateCode(String phone, String template){
        String key = String.format(format, phone, template);
        getInstance().invalidate(key);
    }
    public static void main(String[] args) throws InterruptedException {

        CodeCacheUtils utils = new CodeCacheUtils();
        utils.getInstance().put("1", "1");
        System.out.println(utils.getInstance().getIfPresent("1"));
        Thread.sleep(2 * 1000);
        System.out.println(utils.getInstance().getIfPresent("1"));

        utils = new CodeCacheUtils();
        utils.getInstance().put("2", "2");
        System.out.println(utils.getInstance().getIfPresent("1"));
        System.out.println(utils.getInstance().getIfPresent("2"));
    }
}
